package com.diy.task.common.handler;

import com.diy.task.common.base.BaseResult;
import com.diy.task.common.config.SpringManager;
import com.diy.task.common.exception.BizExceptionEnum;
import com.diy.task.common.exception.BussinessException;
import com.diy.task.sys.entity.AuthUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class SessionHandler {

    private static List<String> list = new ArrayList<>();

    static {
        list.add("/sys/auth-user/account");
        list.add("/sys/auth-user/login");
        list.add("/swagger-ui.html");
        list.add("/swagger-resources");
        list.add("/swagger-resources/configuration/ui");
        list.add("/swagger-resources/configuration/security");
        list.add("/v2/api-docs");
    }

    @ModelAttribute
    public AuthUser getUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String urlStr = request.getRequestURI();

        String authsessionId = request.getHeader("authsessionId");

//        authsessionId = "B12425B6F15E16B9EB61BECB9E89B957";

        //从Redis中获取key为“user”的用户
        AuthUser user = null;
        RedisTemplate redisTemplate = SpringManager.getBean("redisTemplate");
        if (authsessionId != null) {
            user = (AuthUser) redisTemplate.opsForValue().get(authsessionId);
        }
        //如果Redis中没有user登录用户信息，并且该请求不是login登录跳转请求的话，返回501表示未登录
        if (user == null && !list.contains(urlStr)) {
            user = new AuthUser();
            user.setUserName("gjq");
//            throw new BussinessException(BizExceptionEnum.NO_LOGIN);
        }
        return user;
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public BaseResult handException(HttpServletRequest request, Exception e) {
        if (e instanceof BussinessException) {
            return BaseResult.error(((BussinessException) e).getCode(), ((BussinessException) e).getMsessage());
        }
        return BaseResult.error(e.getMessage());
    }

}
